import axios from "axios";
import { Message } from "element-ui"; // MessageBox
import store from "@/store";
// import router from "@/router";
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  timeout: 20000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers['X-Token'] = getToken()
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    // if the custom code is not '10000', it is judged as an error.
    if (res.code !== "10000") {
      Message({
        message: res.msg || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(new Error(res.msg || "Error"));
    } else {
      return res;
    }
  },
  async (error) => {
    if (error && error.request && error.request.status === 401) {
      Message({
        message: "登录超时",
        type: "error",
        duration: 5 * 1000,
      });
    } else {
      let msg = "出错了";
      if (error && error.request && error.request.response) {
        try {
          const parsedResp = JSON.parse(error.request.response);
          parsedResp && parsedResp.msg && (msg = parsedResp.msg);
        } catch (error) {
          console.log(error);
        }
      }
      Message({
        message: msg,
        type: "error",
        duration: 5 * 1000,
      });
    }
    return Promise.reject(error);
  }
);

export default service;
